package com.wcity.manage.web.community;

import com.wcity.manage.common.context.Constants;
import com.wcity.manage.common.context.SessionKey;
import com.wcity.manage.common.enums.Code;
import com.wcity.manage.common.exception.CustomException;
import com.wcity.manage.common.utils.DwzUtil;
import com.wcity.manage.common.utils.JSONUtil;
import com.wcity.manage.common.utils.RespUtil;
import com.wcity.manage.common.utils.request.RequestUtil;
import com.wcity.manage.common.vo.community.permit.PermitPartitionVo;
import com.wcity.manage.common.vo.community.permit.PermitVo;
import com.wcity.manage.dao.dal.model.PageModel;
import com.wcity.manage.dao.model.Block;
import com.wcity.manage.dao.model.User;
import com.wcity.manage.dao.model.community.permit.PermitPartition;
import com.wcity.manage.service.BlockService;
import com.wcity.manage.service.RegisterService;
import com.wcity.manage.service.community.permit.PermitPartitionService;
import com.wcity.manage.service.community.permit.PermitService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 证件类型细分细分
 * Created by hgg on 2016/12/17.
 */
@Controller
public class PermitPartitionAct {

    private final static Logger log = LoggerFactory.getLogger( PermitPartitionAct.class );

    @Autowired
    private PermitPartitionService permitPartitionService;

    @Autowired
    private PermitService permitService;

    @Autowired
    private RegisterService registerService;

    @Autowired
    private BlockService blockService;

    /**
     * 证件类型细分列表
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/community_permitPartition_list")
    public String permitPartitionList( HttpServletRequest request, PageModel model,HttpServletResponse response ) {

        try {

            //【1】获取用户
            User user = (User) request.getSession().getAttribute(SessionKey.SESSION_USER_INFO);
            if ( user == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", ""));
                return "community/permitpartition/list";
            }

            //【2】封装参数/参数校验
            Map<String, Object> requestMap = RequestUtil.getGetData( request );

            //【3】查询数据
            requestMap.put( "start", ( model.getPageNum() - 1) * model.getNumPerPage() );
            requestMap.put( "end", model.getNumPerPage() );
            requestMap.put( "userId", user.getId() );
            List<PermitPartitionVo> permitPartitionVos = permitPartitionService.permitPartitionPageList( requestMap );

            //【4】查询总数量
            Integer totalPermitPartition = permitPartitionService.totalPermitPartition( requestMap );
            model.setTotal( totalPermitPartition );

            request.setAttribute( "permitPartitions", permitPartitionVos );
            request.setAttribute( "pageModel", model );
            request.setAttribute( "partitionName", requestMap.get( "partitionName" ) );
            request.setAttribute( "permitId", requestMap.get( "permitId" ) );

            //【5】查询证件类型列表
            requestMap.clear();
            requestMap.put( "userId",user.getId() );
            List<PermitVo> permits = permitService.permitList( requestMap );
            request.setAttribute( "permits",permits );
        } catch ( Exception e ) {
            log.error( "查询证件类型细分列表异常:" + e.getMessage() );
        }
        return "community/permitpartition/list";
    }

    /**
     * 执行删除证件类型细分
     *
     * @param request
     */
    @RequestMapping(value = "delete_community_permitPartition")
    @ResponseBody
    public void deletePermitPartition( HttpServletRequest request, HttpServletResponse response ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "删除成功";
        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if (requestMap.get("id") == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "请选择一条记录", "", "", "", ""));
                return;
            }

            //【2】执行删除
            Integer deleteNum = permitPartitionService.deletePermitPartition(requestMap);
            if ( deleteNum == 0 ) {
                code = Constants.STATUS_ERROR_DWZ;
                message = "删除失败";
            }
        } catch ( Exception e ) {
            log.error( "删除证件类型细分异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "删除失败";
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, message, "", "", "", ""));
    }

    /**
     * 新增证件类型细分
     *
     * @param permitPartition
     * @param response
     */
    @RequestMapping(value = "save_add_community_permitPartition")
    @ResponseBody
    public void addPermitPartition(PermitPartition permitPartition, HttpServletResponse response, HttpServletRequest request ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "保存成功";

        try {
            //【1】校验参数
            if ( StringUtils.isBlank( permitPartition.getPartitionName() ) || permitPartition.getPermitId() == 0
                    || permitPartition.getPermitId() == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "参数错误", "", "", "", ""));
                return;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute(SessionKey.SESSION_USER_INFO);
            if ( user == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", ""));
                return;
            }

            //【3】执行保存证件类型细分
            permitPartition.setUserId( user.getId() );
            permitPartitionService.saveAddPermitPartition( permitPartition );

        } catch ( Exception e ) {
            log.error( "保存证件类型细分异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "保存失败";
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, message, "community_permitPartition_list", "", "closeCurrent", ""));
    }

    /**
     * 跳转到编辑证件类型细分页面
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "to_edit_community_permitPartition")
    public String permitPartitionDetail( HttpServletRequest request, HttpServletResponse response ) {

        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if ( requestMap.get("id") == null ) {
                return null;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if ( user == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【3】查询证件类型细分数据
            requestMap.put("userId", user.getId());
            PermitPartitionVo permitPartitionVo = permitPartitionService.permitPartitionDetail(requestMap);
            request.setAttribute("permitPartition", permitPartitionVo);
            if (permitPartitionVo == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "数据不存在", "", "", "", ""));
                return null;
            }

            //【4】查询证件类型列表
            requestMap.clear();
            requestMap.put( "userId",user.getId() );
            List<PermitVo> permits = permitService.permitList( requestMap );
            request.setAttribute( "permits",permits );
        } catch ( Exception e ) {
            log.error( "查询证件类型细分失败: " + e.getMessage() );
            RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "查询失败", "", "", "", ""));
        }

        return "community/permitpartition/edit";
    }

    /**
     * 更新证件类型细分
     *
     * @param permitPartition
     * @param response
     */
    @RequestMapping(value = "save_edit_community_permitPartition")
    @ResponseBody
    public void updatePermitPartition(PermitPartition permitPartition, HttpServletResponse response, HttpServletRequest request) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "更新成功";

        try {

            //【1】校验参数
            if ( StringUtils.isBlank( permitPartition.getPartitionName() ) || permitPartition.getPermitId() == 0 ||
                    permitPartition.getPermitId() == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "参数错误", "", "", "", ""));
                return;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute(SessionKey.SESSION_USER_INFO);
            if (user == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", ""));
                return;
            }

            //【3】执行更新证件类型细分
            permitPartition.setUserId( user.getId() );
            Integer updateNum = permitPartitionService.saveUpdatePermitPartition( permitPartition );
            if ( updateNum == 0 ) {
                throw new RuntimeException( "更新证件类型细分失败" );
            }

        } catch ( Exception e ) {
            log.error( "更新证件类型细分异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "更新失败";
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, message, "community_permitPartition_list", "", "closeCurrent", ""));
    }

    /**
     * 跳转到添加证件类型细分的页面
     * @return
     */
    @RequestMapping(value = "to_add_community_permitPartition")
    public String toAddPermitPartition( HttpServletRequest request,HttpServletResponse response ){

        try {

            //【1】获取用户
            User user = (User) request.getSession().getAttribute(SessionKey.SESSION_USER_INFO);
            if ( user == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", ""));
                return "community/permitpartition/add";
            }

            //【2】封装参数/参数校验
            Map<String, Object> requestMap = RequestUtil.getGetData(request);

            //【3】查询证件类型列表
            requestMap.clear();
            requestMap.put( "userId",user.getId() );
            List<PermitVo> permits = permitService.permitList( requestMap );
            request.setAttribute( "permits",permits );
        } catch ( Exception e ) {
            log.error( "跳转到添加证件类型细分的页面:" + e.getMessage() );
        }
        return "community/permitpartition/add";
    }

    /*********************************************H5端请求****************************************/

    /**
     * 证件类型细分列表(H5)
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "v1/community_permitPartition_list_H5")
    @ResponseBody
    public Object permitPartitionListH5( HttpServletRequest request, PageModel model,HttpServletResponse response ) {

        try {

            //【1】封装参数/参数校验
            Map<String,Object> requestMap = new HashedMap();
            String registerId = request.getParameter( "registerId" );
            String permitId = request.getParameter( "permitId" );
            String partitionName = request.getParameter( "partitionName" );
            if( StringUtils.isBlank( registerId ) ){
                throw new CustomException( Constants.PARAMETER_ERROR, Code.ERROR );
            }
            if( StringUtils.isBlank( partitionName ) && StringUtils.isBlank( permitId ) ){
                throw new CustomException( Constants.PARAMETER_ERROR, Code.ERROR );
            }

            //【2】获取当前用户信息
            Map<String,Object> userMap = (Map<String,Object>)registerService.registerInfo( registerId );
            if( userMap == null || userMap.get( "blockId" ) == null ){
                throw new CustomException( "用户信息不存在", Code.ERROR );
            }

            //【3】查询小区
            Integer blockId = (Integer) userMap.get( "blockId" );
            Block block = blockService.getBlockById( blockId );

            //【4】查询数据
            requestMap.put( "start", ( model.getPageNum() - 1 ) * model.getNumPerPage() );
            requestMap.put( "end", model.getNumPerPage() );
            requestMap.put( "userId",block.getUserId() );
            requestMap.put( "permitId",permitId );
            List<PermitPartitionVo> permitPartitionVos = permitPartitionService.permitPartitionPageList( requestMap );

            //【4】查询总数量
            Integer totalPermitPartition = permitPartitionService.totalPermitPartition( requestMap );
            model.setTotal( totalPermitPartition );

            Map<String,Object> map = JSONUtil.getSuccessJson();
            map.put( "data",permitPartitionVos );
            map.put( "pageModel", model );
            return map;
        } catch ( Exception e ) {
            log.error( "证件类型细分列表(H5):" + e.getMessage() );
            return null;
        }
    }

}
